package util

import (
	"fmt"
	"github.com/mix-go/dotenv"
	"github.com/mojocn/base64Captcha"
	"image/color"
	"log"
	_ "mytest/dotenv"
)

var captchaStore string

func init() {
	captchaStore = dotenv.Getenv("CAPTCHA_STORE").String()
	if captchaStore == "REDIS" {
		base64Captcha.SetCustomStore(store)
	} else {
		captchaStore = "MEM"
	}
}

type storeByRedis struct{}

func (s *storeByRedis) Set(id string, value string) {
	key := "captcha:" + id
	err := Redigo.SetEx(key, value, 600)
	if err != nil {
		log.Fatal(fmt.Sprintf("redis存储验证码失败，err：%s", err.Error()))
	}
}

func (s *storeByRedis) Get(id string, clear bool) string {
	value, err := Redigo.Get(id)
	if err != nil {
		//logger.Errorf("redis获取验证码失败，err：%s", err.Error())
		return ""
	}
	if clear {
		_ = Redigo.Del(id)
	}
	return value
}

func (s *storeByRedis) Verify(id, answer string, clear bool) bool {
	key := "captcha:" + id
	value := s.Get(key, clear)
	if len(value) < 0 || value != answer {
		return false
	}
	if clear {
		_ = Redigo.Del(id)
	}
	return true
}

//var store = base64Captcha.DefaultMemStore
var store = &storeByRedis{}

func CreatCaptcha(captchaType string) (id string, b64s string, err error) {

	idkey := string(RandHex(5))
	switch captchaType {
	case "audio":
		var configA = base64Captcha.ConfigAudio{
			CaptchaLen: 6,
			Language:   "zh",
		}
		cid, capA := base64Captcha.GenerateCaptcha(idkey, configA)
		b64s = base64Captcha.CaptchaWriteToBase64Encoding(capA)
		id = cid
	case "string":
		var configC = base64Captcha.ConfigCharacter{
			Height: 30,
			Width:  60,
			//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,
			//CaptchaModeNumberAlphabet:数字字母混合.CaptchaModeUseSequencedCharacters:重复字符
			//CaptchaModeChinese:中文.
			Mode:               base64Captcha.CaptchaModeAlphabet,
			ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
			ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
			IsUseSimpleFont:    true,
			IsShowHollowLine:   false,
			IsShowNoiseDot:     false,
			IsShowNoiseText:    false,
			IsShowSlimeLine:    false,
			IsShowSineLine:     false,
			CaptchaLen:         4,
			SequencedCharacters: []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i",
				"o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"},
			BgColor: &color.RGBA{
				R: 3,
				G: 102,
				B: 214,
				A: 125,
			},
		}
		cid, capC := base64Captcha.GenerateCaptcha(idkey, configC)
		b64s = base64Captcha.CaptchaWriteToBase64Encoding(capC)
		id = cid
	case "math":
		var configC = base64Captcha.ConfigCharacter{
			Height: 30,
			Width:  60,
			//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,
			//CaptchaModeNumberAlphabet:数字字母混合.CaptchaModeUseSequencedCharacters:重复字符
			//CaptchaModeChinese:中文.
			Mode:               base64Captcha.CaptchaModeArithmetic,
			ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
			ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
			IsUseSimpleFont:    true,
			IsShowHollowLine:   false,
			IsShowNoiseDot:     false,
			IsShowNoiseText:    false,
			IsShowSlimeLine:    false,
			IsShowSineLine:     false,
			CaptchaLen:         4,
			BgColor: &color.RGBA{
				R: 3,
				G: 102,
				B: 214,
				A: 125,
			},
		}
		cid, capC := base64Captcha.GenerateCaptcha(idkey, configC)
		b64s = base64Captcha.CaptchaWriteToBase64Encoding(capC)
		id = cid
	case "chinese":
		var configC = base64Captcha.ConfigCharacter{
			Height: 20,
			Width:  100,
			//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,
			//CaptchaModeNumberAlphabet:数字字母混合.CaptchaModeUseSequencedCharacters:重复字符
			//CaptchaModeChinese:中文.
			Mode:                   base64Captcha.CaptchaModeChinese,
			ComplexOfNoiseText:     base64Captcha.CaptchaComplexLower,
			ComplexOfNoiseDot:      base64Captcha.CaptchaComplexLower,
			IsUseSimpleFont:        true,
			IsShowHollowLine:       false,
			IsShowNoiseDot:         false,
			IsShowNoiseText:        false,
			IsShowSlimeLine:        false,
			IsShowSineLine:         false,
			CaptchaLen:             4,
			ChineseCharacterSource: "大威天龙世尊地藏",
		}
		cid, capC := base64Captcha.GenerateCaptcha(idkey, configC)
		b64s = base64Captcha.CaptchaWriteToBase64Encoding(capC)
		id = cid
	case "digit":
		fallthrough
	default:
		var configD = base64Captcha.ConfigDigit{
			Height:     80,
			Width:      240,
			MaxSkew:    0.7,
			DotCount:   80,
			CaptchaLen: 5,
		}
		cid, capD := base64Captcha.GenerateCaptcha(idkey, configD)
		b64s = base64Captcha.CaptchaWriteToBase64Encoding(capD)
		id = cid
	}
	return id, b64s, err
}

func VerifyCaptcha(id, VerifyValue string) bool {
	if captchaStore == "REDIS" {
		if !store.Verify(id, VerifyValue, true) {
			return false
		}
	} else {
		if !base64Captcha.VerifyCaptchaAndIsClear(id, VerifyValue, true) {
			return false
		}
	}
	return true
}
